package com.java.code.xml;

import org.dom4j.*;
import org.dom4j.io.SAXReader;
import org.junit.Test;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Iterator;
import java.util.List;

public class Dom4jUtils {

    /**
     * 读取整个XML
     *
     * @throws Exception
     */
    @Test
    public void parseXml() throws Exception {
        // 创建Reader对象
        SAXReader reader = new SAXReader();
        // 创建输入流
        InputStream in = new FileInputStream(new File("src/main/java/com/wei/code/xml/example.xml"));
        // 加载XML文件
        Document document = reader.read(in);
        // 获取根节点
        Element rootElement = document.getRootElement();
        // 遍历节点
        Iterator<Element> iterator = rootElement.elementIterator();
        ;
        while (iterator.hasNext()) {
            // 获取student节点
            Element studentElement = iterator.next();
            // 遍历student节点的属性
            List<Attribute> attributeList = studentElement.attributes();
            ;
            for (Attribute attribute : attributeList) {
                System.out.println("属性: " + attribute.getName() + "=" + attribute.getValue());
            }
            // 获取student节点的子节点
            List<Element> studentSubElementList = studentElement.elements();
            ;
            // 遍历student节点的子节点
            for (Element sub : studentSubElementList) {
                System.out.println("节点: " + sub.getName() + "=" + sub.getStringValue());
            }
            System.out.println("=========================");
        }

    }

    /**
     * 通过xpath获取xml节点
     *
     * @throws Exception
     */
    @Test
    public void getNodeData() throws Exception {
        // 创建Reader对象
        SAXReader reader = new SAXReader();
        // 创建输入流
        InputStream in = new FileInputStream(new File("src/main/java/com/wei/code/xml/example.xml"));
        // 加载XML文件
        Document document = reader.read(in);
        Node node = document.selectSingleNode("/class/student/firstname");
        System.out.println(node.getText());

    }

    /**
     * 通过xpath获取xml节点
     *
     * @throws Exception
     */
    @Test
    public void getXmlStringNode() throws Exception {
        String xmlString = "<?xml version= '1.0' encoding='utf-8'?><weighData>123</weighData>";
        Document document = DocumentHelper.parseText(xmlString);
        Element ele = (Element) document.selectSingleNode("//weighData");
        System.out.println(ele.getTextTrim());
    }
}
